import ImportData from "@/components/ImportData";
import { s_freezeShipping, s_getSaleInfo, s_getSelectData, s_getShippingInfo, s_getTableInfo, s_operateInfo, s_saveShippingInfo, s_updateInfo } from "@/services/basis";
import { ActionType, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProTable, TableDropdown } from "@ant-design/pro-components";
import { useModel } from "@umijs/max";
import { Button,Image, Card, Col, message, Modal, Row, Space, Table, TableColumnProps, Tag, Typography } from "antd";
import moment from "moment";
import React, { useRef, useState } from "react";
// import styles from 'global.less';

const App:React.FC=()=>{
    const [selectedRows,setSelectedRows]=useState<DataType[]>([]);
    const [selectedRowKeys,setSelectedRowKeys]=useState<React.Key[]>([]);
    const [open,setOpen]=useState(false);
    const [etype,setEtype]=useState(0);

    const table_ref=useRef<ActionType>();
    const form_ref=useRef<ProFormInstance>();
    const [total,setTotal]=useState(0);

    const { initialState, setInitialState } = useModel('@@initialState');
    const [selectedLineKeys,setSelectedLineKeys]=useState<any[]>([]);

    interface DataType{
        x_id?:number,
        id?:number,
        custom_id?:string,
        custom_name?:string,
        material_id?:string,
        code?:string,
        name?:string,
        custom_sku?:string,
        fn_sku?:string,
        ansi_sku?:string,
        status?:number,
        operate_time?:string,
        operater_id?:number,
    }
    const columns:ProColumns<DataType>[]=[
        {dataIndex:'x_id',hidden:true,search:false},
        {key:'id',dataIndex:'id',title:'ID',hidden:true,search:false},
        {dataIndex:'pic',title:'图片' ,editable:false,width:60,search:false,
              render:(text,record,index,k)=>{
                     var pic="/basis_api/file/get2?filename="+record.code;
                     return   <Image src={pic}  style={{width:50,height:50}} alt='无' />
                 }},
        {dataIndex:'custom_name',title:'店铺'},
        {dataIndex:'code',title:'商品SKU'},
        {dataIndex:'name',title:'商品名称'}, 
        {dataIndex:'custom_sku',title:'店铺SKU',search:false},
        {dataIndex:'fn_sku',title:'FN_SKU',search:false},
        {dataIndex:'ansi_sku',title:'ANSIN_SKU',search:false},
        {dataIndex:'status',title:'状态',search:false,
            render:(text)=>text==1?<>正常</>:text==2
                ?<Tag style={{color:'blue'}}>冻结</Tag>:<Tag style={{color:'red'}}>删除</Tag>},
    ];
     
    async function add(){
        setSelectedRowKeys([]);
        setEtype(1);
        setOpen(true);
    }
    async function edit(){
        if(selectedRowKeys.length==0)
            message.warning('请先选择要编辑的行。');
        else if(selectedRows[0].status==2||selectedRows[0].status==3)
            message.warning('已关闭、删除的记录不能编辑。请先恢复');
        else{
            setEtype(0);
            setOpen(true);
        }
    }
    async function save(){
        setOpen(false);
        setSelectedRowKeys([]);
        const fdata2=form_ref.current?.getFieldsValue();
        const fdata={...fdata2,
            operate_time:moment(moment(fdata2.operate_time).toDate()).format('YYYY-MM-DD HH:mm:ss'),
        }
        //source,x_id,operater_id,etype,fdata  通用的表格保存
        const x=await s_updateInfo({source:'base_materialcodes',x_id:1,operater_id:initialState?.currentUser?.userid,etype,fdata});
        if(x.success){
            message.success('数据保存成功。');
            setOpen(false);
            setEtype(1);
            table_ref.current?.reloadAndRest?.();
        }else
           message.error('数据保存失败，请检查。');
    }

    async function operate(otype:number){
        const id=selectedRows[0].id;
        //s_operateInfo({source:'base_ware',operater_id:initialstate?.currentuser?.userid,type:tabKey,otype,id})通用表格操作冻结删除
        const x=await s_operateInfo({source:'base_materialcodes',x_id:1,operater_id:initialState?.currentUser?.userid,otype,id});

        if(x.success){
            message.success('更新成功。');
            table_ref.current?.reloadAndRest?.();
        }else
           message.error('更新失败，请联系管理员。');
    }
    

    return (
        <>
        <ProCard title='商品SKU对照表' style={{height:'75vh',overflow:'auto'}} 
        extra={<Space>
            <Button onClick={()=>add()}>新增</Button>
            <Button onClick={()=>edit()}>编辑</Button>
            
            <Button onClick={()=>operate(2)}>关闭</Button>
            <Button onClick={()=>operate(3)}>删除</Button>
            <Button onClick={()=>operate(1)}>恢复</Button>
            <ImportData  x_id={1} source='importdata' tdata={{data:'materialcodes'}}
                  operater_id={initialState?.currentUser?.userid}  /> 
            </Space>}>
            {/* {JSON.stringify(selectedRows)}  */}
            <ProTable<DataType> 
            actionRef={table_ref}
            search={{span:5}} 
            columns={columns}
            rowKey='id'
            rowSelection={{
                type:'radio',
                selectedRowKeys:selectedLineKeys,
                onChange:(selectedRowKeys,selectedRows)=>{
                    setSelectedRows(selectedRows);
                    setSelectedRowKeys(selectedRowKeys);
                    setSelectedLineKeys(selectedRowKeys);
                },
            }}
             onRow={(record)=>{
              return {
              onClick:()=>{
                const k=record.id;
                // if(selectedKeys.includes(k) )
                //      setSelectedKeys(selectedKeys.filter(item=>item.id!=k));
                // else
                     setSelectedRowKeys([k]);
                     setSelectedRows([record]);
                     setSelectedLineKeys(selectedRowKeys);
              },
            }
           }}
            request={async (param)=>{
                var id=0;
                if(selectedRowKeys.length!=0)
                    id=Number.parseInt(selectedRowKeys[0].toString());
                // const x=await s_getTableInfo({source:'v_materialcodes',x_id:1,id:id});  //通用的表格取数函数
                const x=await s_getSaleInfo({source:'v_materialcodes',x_id:1,id,fdata:{id:0,param}});
                setTotal(x.data[0][0].count);
                  return{
                     data:x.data[1],
                     success:true,
              }
            }}
            scroll={{
                y:430,
            }}
            pagination={{
                pageSize:9,
            }}
        
        />
        <Modal title={etype==0?'编辑商品对照':'新增商品对照'} destroyOnClose closable onCancel={()=>setOpen(false)}
            open={open} onOk={()=>form_ref.current?.submit()} width='50%'
        >
             <ProForm submitter={false} formRef={form_ref}   
               onFinish={()=>save()}
               initialValues={etype==1?{
                       operate_time:moment().format('YYYY-MM-DD'),
                       operater_id:initialState?.currentUser?.userid,status:1,
                   }:{
                      ...selectedRows[0],
                 }}
             >
                <ProFormText name='x_id' hidden/>
                <ProFormText name='id' hidden/>
                <Row gutter={8}>
                    <Col span={8}>
                        <ProFormSelect name='custom_id' label='店铺' rules={[{required:true,message:'必输项'}]}
                            showSearch width={300}
                            request={async ()=>{
                            const x=await s_getSelectData({x_id:1,source:'v_custom'});
                                 return x.data;}}
                           />
                    </Col>
                    <Col span={8}>
                        <ProFormSelect name='material_id' label='商品SKU' rules={[{required:true,message:'必输项'}]}
                          showSearch width={300}
                          request={async ()=>{
                          const x=await s_getSelectData({x_id:1,source:'vmaterial'});
                          return x.data;}}
                  />
                    </Col>
                    
                </Row>
                <Row gutter={8}>
                    <Col span={8}>
                         <ProFormText name='custom_sku' label='店铺SKU'  width={300}
                         rules={[{required:true,message:'必输项'}]}/>
                    </Col>
                    <Col span={8}>
                       <ProFormText name='fn_sku' label='FN_SKU'   width={300}
                       rules={[{required:true,message:'必输项'}]}/>
                    </Col>
                    <Col span={8}>
                        <ProFormText name='ansi_sku' label='ANSIN_SKU'  width={300}
                        rules={[{required:true,message:'必输项'}]}/>
                    </Col>
                </Row>
                <Row gutter={8}>
                    <Col span={8}>
                        <ProFormRadio.Group name='status' label='状态'
                              options={[{label:'正常',value:1},{label:'冻结',value:2,style:{color:'blue'}},
                             {label:'删除',value:3,style:{color:'red'}}]}
                          />
                    </Col>
                    <Col span={8}>
                          <ProFormDatePicker name='operate_time' label='操作时间'  width={300}/>
                    </Col>
                    <Col span={8}>
                          <ProFormSelect name='operater_id' label='操作人' width={300}
                                 showSearch
                                 request={async ()=>{
                               const x=await s_getSelectData({x_id:1,source:'base_person'});
                                return x.data;}}
                          />
                    </Col>
                </Row>
                
               
                
             </ProForm>
        </Modal>
        </ProCard>
        </>
    );
}

export default App;